﻿package  Cain.youTube
{
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.system.Security;
	
	/**
	 * 使用youtube影片 v1.1
	 * @author Cain
	 */
	public class YouTube extends Sprite
	{ 
		/**
		 * 撥放狀態改變事件;
		 */
		static public const STATE_CHANG:String = "STATE_CHANG";
		/**
		 * 影片撥完
		 */
		static public const PLAYEND:String = "end";
		/**
		 * 找不到影片或是任何錯誤
		 */
		static public const ONERROR:String = "onerror";
		private var loader:Loader;
		/**
		 * youTube api 撥放器
		 */
		public var player:Object;
		private var ww:int;
		private var hh:int;
		private var quality:String;
		public var read_ok:Boolean;
		/**
		 * 輸入YouTube連結,傳回Code
		 * @param	_link
		 * @return
		 */
		static public function urlToCode(_link:String):String 
		{
			var _n:int = _link.indexOf("http://www.youtube.com/watch?v=");
			var _code:String;
			if (_n==0) 
			{
				_code = _link.substr(31, 11);
			}else 
			{
				_code = "not YouTube url";
				trace("not YouTube url");
			}
			return _code;
		}
		/**
		 * 影片建構
		 * 撥放器載入完成時發出"onReady"事件
		 * 撥放完成時發出"end"事件
		 * @param	_ww 寬
		 * @param	_hh 高
		 * @param	_quality 影片品質
		 */
		public function YouTube(_ww:int=400, _hh:int=300, _quality:String ="medium")
		{
			ww = _ww;
			hh = _hh;
			quality = _quality;
			setup();
			addEventListener(Event.ADDED_TO_STAGE, addThis);
		}
		/**
		 * 音量
		 */
		public function set volume(_vol:int):void 
		{
			player.setVolume(_vol);
		}
		public function get volume():int 
		{
			return int(player.getVolume());
		}
		private function setup():void
		{
			try 
			{
				Security.allowDomain("*");
			}catch (err:Error)
			{
				trace("air不需Security.allowDomain");
			}
			
			loader = new Loader();
		}
		
		private function addThis(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, addThis);
			addEventListener(Event.REMOVED_FROM_STAGE, removeThis);
			init();
		}
		
		private function init():void
		{
			loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
			try 
			{
				loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
			}catch (err:Error)
			{
				trace("無法載入撥放器");
			}
			
		}
		
		private function onLoaderInit(e:Event):void 
		{
			addChild(loader);
			loader.content.addEventListener("onReady", onPlayerReady2);
			loader.content.addEventListener("onError", onPlayerError2);
			loader.content.addEventListener("onStateChange", onPlayerStateChange2);
			loader.content.addEventListener("onPlaybackQualityChange", onVideoPlaybackQualityChange2);
			read_ok = true;
		}
		
		private function onPlayerReady2(e:Event):void 
		{
			player = loader.content;
			player.setSize(ww, hh);
			dispatchEvent(new Event("onReady"));
		}
		private function onPlayerError2(event:Event):void {
			// Event.data contains the event parameter, which is the error code
			//trace("player error:", Object(event).data);
			dispatchEvent(new Event(ONERROR));
		}

		private function onPlayerStateChange2(event:Event):void {
			// Event.data contains the event parameter, which is the new player state
			//trace("player state:", Object(event).data);
			dispatchEvent(new Event(STATE_CHANG));
			if (Object(event).data==0) 
			{
				dispatchEvent(new Event("end"));
			}
			
		}

		private function onVideoPlaybackQualityChange2(event:Event):void {
			// Event.data contains the event parameter, which is the new video quality
			//trace("video quality:", Object(event).data);
		}
		private function removeThis(e:Event):void 
		{
			removeEventListener(Event.REMOVED_FROM_STAGE, removeThis);
			loader.content.removeEventListener("onReady", onPlayerReady2);
			loader.content.removeEventListener("onError", onPlayerError2);
			loader.content.removeEventListener("onStateChange", onPlayerStateChange2);
			loader.content.removeEventListener("onPlaybackQualityChange", onVideoPlaybackQualityChange2);
		}
		/**
		 * 影片載入並撥放
		 * @param	_str ID
		 * @param	_s 影片位置
		 */
		public function loadAndPlay(_str:String,_s:int=0):void
		{
			try 
			{
				player.loadVideoById(_str,_s,quality);
			}catch (err:Error)
			{
				
			}
			
		}
		/**
		 * 影片載入
		 * @param	_str ID
		 * @param	_s 影片位置
		 */
		public function load(_str:String,_s:int=0):void
		{
			player.cueVideoById(_str,_s,quality)
		}
		/**
		 * 撥放
		 */
		public function play():void 
		{
			player.playVideo();
		}
		/**
		 * 停止
		 */
		public function stop():void 
		{
			try 
			{
				player.pauseVideo();
			}catch (err:Error)
			{
				
			}
		}
		/**
		 * 停止並移除正在載入的影片
		 */
		public function unload():void 
		{
			player.stopVideo();
		}
		/**
		 * 取得目前撥放影片的狀態
		 * 未開始（-1），結束（0），玩（1），暫停（2），緩衝（3），視頻線索（5）
		 */
		public function get state():int 
		{
			return player.getPlayerState();
		}
	}

}